<template>
	<div class="sys-notice-container">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item label="时间范围">
					<el-date-picker v-model="dateRange" type="datetimerange" range-separator="到" start-placeholder="开始时间"
						end-placeholder="结束时间" />
				</el-form-item>
				<el-form-item label="项目名称">
					<el-input v-model="state.queryParams.name" placeholder="标题" clearable />
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="handleQuery"> 查询 </el-button>
						<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
					</el-button-group>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="ele-Plus" @click="openAddProject"> 新增 </el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<el-card class="full-table" shadow="hover" style="margin-top: 8px">
			<el-table :data="state.projectlist" style="width: 100%" show-summary v-loading="state.loading" border
				:summary-method="getSummaries">
				<!-- <el-table-column type="index" label="序号" width="55" align="center" /> -->
				<el-table-column prop="name" label="项目名称" show-overflow-tooltip />
				<el-table-column prop="orgName" width="130" label="所属部门" align="center" show-overflow-tooltip />
				<el-table-column prop="projectTime" width="130" label="项目工时/小时" align="center" show-overflow-tooltip />
				<el-table-column prop="productTime" width="130" label="产品工时/小时" align="center" show-overflow-tooltip />
				<el-table-column prop="frontTime" width="130" label="前端工时/小时" align="center" show-overflow-tooltip />
				<el-table-column prop="backendTime" width="130" label="后端工时/小时" align="center" show-overflow-tooltip />
				<el-table-column prop="totalTime" width="130" label="总计/小时" align="center" show-overflow-tooltip />
				<el-table-column prop="cost" width="130" label="内部成本/元" align="right" show-overflow-tooltip>
					<template #default="scope">
						{{ toThousands(scope.row.cost) }}
					</template>
				</el-table-column>
				<el-table-column prop="opt" label="操作" width="200" fixed="right" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary" @click="openEditProject(scope.row.id)">
							编辑 </el-button>
						<el-button icon="ele-EditPen" size="small" text type="info" @click="OverProjects(scope.row.id)"> 报结
						</el-button>
						<el-button icon="ele-Remove" size="small" text type="danger" @click="delProjects(scope.row.id)"> 删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<el-pagination v-model:currentPage="state.tableParams.page" v-model:page-size="state.tableParams.pageSize"
				:total="state.tableParams.total" :page-sizes="[10, 20, 50, 100]" small background
				@size-change="handleSizeChange" @current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper" />
		</el-card>

		<AddProject ref="addProjectRef" title="新增项目" @handleQuery="handleQuery" />
		<EditProject ref="editProjectRef" title="编辑项目" @handleQuery="handleQuery" />
	</div>
</template>

<script lang="ts" setup name="projectlist">
import { onMounted, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import commonFunction from '/@/utils/commonFunction';
import AddProject from '/@/views/business/project/component/addProject.vue';
import EditProject from '/@/views/business/project/component/editProject.vue';

import { getProjects, delProject, OverProject } from '/@/api/business/project'
import { SysNoticeApi } from '/@/api-services/api';

interface SummaryMethodProps<T = Product> {
	columns: TableColumnCtx<T>[]
	data: T[]
}
const addProjectRef = ref<InstanceType<typeof AddProject>>();
const editProjectRef = ref<InstanceType<typeof EditProject>>();
const { removeHtml } = commonFunction();
const state = reactive({
	loading: false,
	queryParams: {
		name: undefined,
	},
	tableParams: {
		page: 1,
		pageSize: 20,
		total: 0 as any,
	},
	projectlist: [] as Array<Object>
	// editNoticeTitle: '',
});
const dateRange = ref('')

onMounted(async () => {
	handleQuery();
});

const toThousands = (num) => {
	var result = [], counter = 0;
	num = (num || 0).toString().split('');
	for (var i = num.length - 1; i >= 0; i--) {
		counter++;
		result.unshift(num[i]);
		if (!(counter % 3) && i != 0) { result.unshift(','); }
	}
	return result.join('');
}

const getSummaries = (param: SummaryMethodProps) => {
	const { columns, data } = param
	const sums: string[] = []
	columns.forEach((column, index) => {
		if (index === 0) {
			sums[index] = '合计'
			return
		} else if (column.property == 'cost') {
			const values = data.map((item) => item[column.property])
			console.log(values);
			sums[index] = `${values.reduce((prev, curr) => {
				const value = Number(curr)
				if (!Number.isNaN(value)) {
					return add(prev,curr)
				} else {
					return prev
				}
			}, 0)}`
			sums[index] = toThousands(sums[index]);
		}  else if (column.property == 'opt' || column.property == 'orgName') {

			sums[index] = '';
		}else {
			const values = data.map((item) => item[column.property])
			sums[index] = `${values.reduce((prev, curr) => {
				const value = Number(curr)
				if (!Number.isNaN(value)) {
					return add(prev,curr)
				} else {
					return prev
				}
			}, 0)}`
		}
	})

	return sums
}

// 查询操作
const handleQuery = async () => {
	state.loading = true;
	let params = Object.assign(state.queryParams, state.tableParams);
	if (dateRange.value != '') {
		params = Object.assign(params, { dataRange: dateRange.value });
	}
	const res = await getProjects(params);
	state.projectlist = res.data.result?.items ?? [];
	// var res = await getAPI(SysNoticeApi).apiSysNoticePagePost(params);
	// state.noticeData = res.data.result?.items ?? [];
	state.tableParams.total = res.data.result?.total;
	state.loading = false;
};

// 重置操作
const resetQuery = () => {
	state.queryParams.name = undefined;
	handleQuery();
};

// 打开新增页面
const openAddProject = () => {
	addProjectRef.value?.openDialog({ type: 1 });
};
// 打开新增页面
const openEditProject = (id: any) => {
	editProjectRef.value?.openDialog({ type: 1, id: id });
};
const delProjects = async (id: any) => {
	await delProject({ id });
	ElMessage.warning('项目删除完成');
	handleQuery();
}

/**
 * 精确加法
 */
 const add = (num1, num2)=> {
  const num1Digits = (num1.toString().split('.')[1] || '').length;
  const num2Digits = (num2.toString().split('.')[1] || '').length;
  const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));
  return (num1 * baseNum + num2 * baseNum) / baseNum;
}


// // 打开编辑页面
// const openEditNotice = (row: any) => {
// 	state.editNoticeTitle = '编辑通知公告';
// 	editNoticeRef.value?.openDialog(row);
// };

// 改变页面容量
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};
const OverProjects = async (id: any) => {
	await OverProject({ id })
	ElMessage.success('项目报结完成');
	handleQuery();
}

// 改变页码序号
const handleCurrentChange = (val: number) => {
	state.tableParams.page = val;
	handleQuery();
};
</script>
